package com.vhall.component.service.account.impl;

import com.vhall.component.framework.common.exception.BusinessException;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @author shimingming
 * @since 2023/7/5 19:45
 */
public class BlowFishUtil {

    private static final String CIPHER_ALG = "Blowfish";
    private static final String CIPHER_MODE = "Blowfish/ECB/NoPadding";
    public static final String KEY_TEXT = "e93d61341cf6c3ab5033e3064ed218d7";

    private static byte[] putZeroPadding(byte[] plaintexts, int blockSize) {
        int length = plaintexts.length;
        //计算需填充长度
        if (length % blockSize != 0) {
            length = length + (blockSize - (length % blockSize));
        }
        byte[] results = new byte[length];
        //填充
        System.arraycopy(plaintexts, 0, results, 0, plaintexts.length);
        return results;
    }

    public static String encrypt(String plaintext) {
        try {
            Cipher cipher = fetchCipher(Cipher.ENCRYPT_MODE);
            return encrypt(plaintext, cipher);
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }

    private static Cipher fetchCipher(int cipherMode) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(KEY_TEXT.getBytes(StandardCharsets.UTF_8), CIPHER_ALG);
        Cipher cipher = Cipher.getInstance(CIPHER_MODE);
        cipher.init(cipherMode, keySpec);
        return cipher;
    }

    private static String encrypt(String plaintext, Cipher cipher) throws Exception {
        // Cipher cipher = fetchCipher(Cipher.ENCRYPT_MODE, keyText);
        int blockSize = cipher.getBlockSize();
        byte[] plaintexts = putZeroPadding(plaintext.getBytes(StandardCharsets.UTF_8), blockSize);

        byte[] encryptedTexts = cipher.doFinal(plaintexts);
        return Hex.encodeHexString(encryptedTexts, false);

    }

}
